const fs = require('fs');  
const path = require('path');  
const { ucs2 } = require('punycode');
const svg2ttf = require('svg2ttf');
const SVGIcons2SVGFontStream = require('svgicons2svgfont');  
const getCss = require('./getCSS');

function getDefaultCssPath(url) {
  if (fs.existsSync(url + '.wxss')) {
    return url + '.wxss';
  } else {
    return url + '.css';
  }
}  
module.exports = function(options) {
  const roots = process.cwd();  // 当前处于fonts文件夹里面
  const dir = path.join(roots, '/src');
  const fontName = options.fontName || 'iconfont';
  const svgPath = path.join(roots, fontName + '.svg');
  const ttfPath = path.join(roots, fontName + '.ttf');
  const defaultCssPath = getDefaultCssPath('../app/assets/css/fonts');
  const cssPath = path.join(roots, options.cssPath || defaultCssPath);
  const codeNum = 57344;
  let glyphList = [];

  const fontStream = new SVGIcons2SVGFontStream({
    fontName: fontName,
    normalize: true
  });

  fontStream.pipe(fs.createWriteStream(svgPath)).on('finish', function() {
    console.log('svg created!');

    // svg创建成功， 再创建ttf
    let ttf = svg2ttf(fs.readFileSync(svgPath, 'utf8'), {});
    fs.writeFileSync(ttfPath, new Buffer(ttf.buffer));
    console.log('ttf created!');

    // ttf创建成功 在转化为base64格式
    let ttfData = fs.readFileSync(ttfPath); 
   
    let base64Data = new Buffer(ttfData).toString('base64');

    fs.readFile(cssPath, 'utf-8', function(err, data) {
      let cssObj = getCss(fontName, base64Data, glyphList);
      if (err) {
        data = cssObj.fontFace + '\n'+ cssObj.fontCss;
      } else {
        let regSrc = /\/\*font-face-start\*\/[\s\S]*\/\*font-face-end\*\//i;
        let reg = new RegExp('\\/\\*font\\-icon\\-start\\*\\/[\\s\\S]*\\/\\*font\\-icon\\-end\\*\\/','i');
        if (!data) {
          data = cssObj.fontFace + '\n'+ cssObj.fontCss;
        }
        if (regSrc.test(data)) {
          data = data.replace(regSrc, cssObj.fontFace);
        } else {
          data = cssObj.fontFace + '\n' + data;
        }
        if (reg.test(data)) {
          data = data.replace(reg, cssObj.fontCss);
        } else {
          data = data + '\n' + cssObj.fontCss;
        }
      }

      fs.writeFileSync(cssPath, data);
      console.log('css created to ' + cssPath);
    });

  }).on('error', function(err) {
    console.log(err);
  });

  fs.readdir(dir, function (err, files) {
    if (err) {
      return console.error(err);
    }
    files.forEach( function (file, i){
      if (/\.svg$/i.test(file)) {
        let glyph = fs.createReadStream(dir + '/' + file);
        let code = ucs2.encode([codeNum + i]); // 直接字符串拼接成ubicode，会被当做字符换，这里需要ucs2转码
        let name = file.split('.')[0];
        glyph.metadata = {
          unicode: [code],  
          name: name
        };
        glyphList.push({ name: name, codePoint: codeNum + i });
        fontStream.write(glyph);
      }
    });
    fontStream.end();
  });
};
